"""Server configuration object"""

import os
import sys
import pathlib
import logging
import tempfile

from pydantic import BaseModel, Field

app_root_dir = str(pathlib.Path(os.path.abspath(__file__)).parent.parent).replace("\\", "/")
server_root_dir = f"{os.path.dirname(os.path.abspath(__file__))}/public".replace("\\", "/")


logging_config = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "minimal": {"format": "%(message)s"},
        "detailed": {"format": "%(levelname)s %(asctime)s [%(name)s:%(filename)s:%(lineno)d]\n%(message)s\n"},
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "stream": sys.stdout,
            "formatter": "minimal",
            "level": logging.DEBUG,
        },
        "info": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": f"{tempfile.gettempdir()}/pkgm/pkgm_info.log",
            "maxBytes": 10485760,  # 1 MB
            "backupCount": 10,
            "formatter": "detailed",
            "level": logging.INFO,
        },
        "error": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": f"{tempfile.gettempdir()}/pkgm/pkgm_error.log",
            "maxBytes": 10485760,  # 1 MB
            "backupCount": 10,
            "formatter": "detailed",
            "level": logging.ERROR,
        },
    },
    "root": {
        "handlers": ["console", "info", "error"],
        "level": logging.INFO,
        "propagate": True,
    },
}


class PkgmConfig(BaseModel):
    """Server configuration"""

    run_model: str = Field(default="debug", description="Run model debug and release")

    http_listen_address: str = Field(
        default="0.0.0.0",
        description="An address the API server listens on",
    )
    http_listen_port: int = Field(
        default=5000,
        description="A port the API server listens on",
    )
    show_title: str = Field(default="pkgm",)
    description: str = Field(default="This tool is designed for managing and resolving package dependencies",)

    cors_origns: list = Field(default=["*"], description="CORS origins")
    cors_allow_credentials: bool = Field(default=True, description="CORS allow credentials")
    cors_allow_methods: list = Field(default=["*"], description="CORS allow methods")
    cors_allow_headers: list = Field(default=["*"], description="CORS allow headers")

    static_dir: str = Field(default=f"{app_root_dir}/resource", description="Static directory")

    user_name: str = Field(default="admin", description="User name")
    user_password: str = Field(default="123456", description="User password")

    sqlite_db_path: str = Field(default=f"{app_root_dir}/pkgm_data.db", description="SQLite database path")

    user_token_expire_days: int = Field(default=7, description="User token expire days")


pkgm_config = PkgmConfig()
logging.config.dictConfig(logging_config)


def reload_config(config_field: dict):
    """Reload configuration"""
    for item in config_field:
        setattr(pkgm_config, item, config_field[item])
